/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db.client.Connection;


import db.client.DTO.EditTableDTO;
import db.client.DTO.QueryDTO;
import db.client.GUI.DBClientQuery;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author QuangKhai
 */
public class ExecuteThread implements Runnable{
    private ObjectOutputStream oos;
    private ObjectInputStream ois;    
    private QueryDTO queryDTO = new QueryDTO();    

    private DBClientQuery query = null;
    public ExecuteThread(Socket socket, DBClientQuery query, ObjectOutputStream oos, ObjectInputStream ois) throws IOException{
        this.queryDTO = query.queryDTO; 
        
        this.query = query;
        this.oos = oos;
        this.ois = ois;      
    }
    
    public void sendType() throws IOException{
        oos.writeUTF("Execute");
        oos.flush();
    }
    
    public void sendQuery(QueryDTO queryDTO) throws IOException{
        oos.writeUTF(queryDTO.getDatabaseName());
        oos.reset();
        oos.writeUTF(queryDTO.getQuerySentences().get(0));        
        oos.reset();
    }
    
    //Hàm nhận ảnh màn hình từ Server
    public EditTableDTO reciveResult() throws IOException, ClassNotFoundException{
        EditTableDTO editTableDTO = new EditTableDTO();
        List<String> lstColumnName = new ArrayList<String>();
        List<List<String>> lstValues = new ArrayList<List<String>>();
        
        int colums = ois.readInt();
        
        for(int i = 0; i < colums; i++){
            lstColumnName.add(ois.readUTF());            
        }
        
        int ivalues = ois.readInt();
        
        for(int i = 0; i < ivalues; i++){
            List<String> values = new ArrayList<String>();
            for(int j = 0; j < colums; j++){
                values.add(ois.readUTF());                
            }
            
            lstValues.add(values);
        }
        
        editTableDTO.setColumnName(lstColumnName);
        editTableDTO.setLstValues(lstValues);
        
        return editTableDTO;
    }
    
    @Override
    public void run() {        
        try {
            sendType();
            sendQuery(queryDTO);
            query.editTableDTO = reciveResult();
            
            query.showResults();
        } catch (IOException ex) {
            Logger.getLogger(ExecuteThread.class.getName()).log(Level.SEVERE, null, ex);
        }catch (ClassNotFoundException ex) {
            Logger.getLogger(ExecuteThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
